import { isUndef } from "../../help";
// "background-color: red";
function stringStyleToObj(stringStyle){
   const style = {};
   const styleArray  = [...stringStyle.matchAll(/\s*([^:]+)\s*:\s*([^;]+)\s*[$|;]*/g)].map(r=>r.slice(1));
   styleArray.forEach(([key, value])=>{
        style[key] = value;
   });
   return style;
}
function normalizeStyleData(data){
    const {staticStyle, style} = data;
    const styleBinding = normalizeStyleBinding(style);
    if (!isUndef(staticStyle)){
        Object.assign(styleBinding, stringStyleToObj(staticStyle));
    }
    return styleBinding;
}
// 动态style属性
/*
1. {backgroundColor: 'red'}
2. [{backgroundColor: 'red'}]
*/
function normalizeStyleBinding(styleBinding){
    if (Array.isArray(styleBinding)){
        let result = {};
        for(let i=0; i<styleBinding.length; i++){
            if (!isUndef(styleBinding[i])){
                Object.assign(result, normalizeStyleBinding(styleBinding[i]));
            }
        }
        return result;
    }
    return styleBinding; 
}
// fontSize == > font-size
function hyphenate(string){
    return string.replace(/\B([A-Z])/g, '-$1').toLowerCase();
}
function setProp(el, key, value){
    // fontSize == > font-size
    el.style.setProperty(hyphenate(key), value);
}
function updateStyle(oldVnode, vnode){
    const oldData = oldVnode.data || {};
    const data = vnode.data || {};
    // <div ></div> 元素没有style的情况, 不用处理了
    if (
        isUndef(oldData.staticStyle) &&
        isUndef(oldData.style) &&
        isUndef(data.staticStyle) &&
        isUndef(data.style)
    ){
        return;
    }
    // 获取最新的style(动态 静态的style都在), 返回值为摊平的对象
    // {backgroundColor: 'red'}
    const style = normalizeStyleData(data);
    const oldStyle = oldData.oldStyleBinding || {};
    let name;
    let elm = vnode.elm;
    // 遍历老的节点, 如果发现在新的节点里已经没了，就要删除了
    for (name in oldStyle){
        if (isUndef(style[name])){
            setProp(elm, name, '');
        }
    }
    // 遍历老的节点, 发现跟老节点不同的情况下, 更新
    for (name in style){
        if (style[name] !== oldStyle[name]){
            setProp(elm, name, style[name]);
        }
    }
    data.oldStyleBinding = style;

}

export default {
    create: updateStyle,
    update: updateStyle
}